import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import '../models/word_card.dart';
import '../models/word_book.dart';
import '../data/word_book_service.dart';
import '../widgets/word_card_widget.dart';
import 'dart:async';

class FollowReadingPage extends StatefulWidget {
  final WordBook wordBook;
  final List<WordCard> words;

  const FollowReadingPage({
    Key? key,
    required this.wordBook,
    required this.words,
  }) : super(key: key);

  @override
  _FollowReadingPageState createState() => _FollowReadingPageState();
}

class _FollowReadingPageState extends State<FollowReadingPage> {
  final AudioPlayer _audioPlayer = AudioPlayer();
  int _currentIndex = 0;
  bool _showDetails = false;
  bool _isLastRepetition = false;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _checkIfLastRepetition();
    if (widget.words.isNotEmpty) {
      _playWhatsThis();
    }
  }

  @override
  void dispose() {
    _audioPlayer.dispose();
    _timer?.cancel();
    super.dispose();
  }

  void _checkIfLastRepetition() {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    setState(() {
      _isLastRepetition = word.repeatCount == 4; // 第5次重复（从0开始计数）
    });
  }

  void _playWhatsThis() {
    if (_isLastRepetition) {
      _audioPlayer.play(AssetSource('data/audio/whats-this.mp3'));
    } else {
      _showDetailsAfterDelay();
    }
  }

  void _playWordAudio() {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    _audioPlayer.play(UrlSource('https://ali.bczcdn.com/r/${word.wordAudio}'));
  }

  void _showDetailsAfterDelay() {
    _timer?.cancel();
    _timer = Timer(Duration(seconds: 5), () {
      setState(() {
        _showDetails = true;
      });
      _playWordAudio();
    });
  }

  void _onCardTap() {
    if (_isLastRepetition && !_showDetails) {
      setState(() {
        _showDetails = true;
      });
      _playWordAudio();
    } else if (!_isLastRepetition) {
      _timer?.cancel();
      setState(() {
        _showDetails = true;
      });
      _playWordAudio();
    }
  }

  void _onRemembered() async {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    await WordBookService.moveWordToReview(widget.wordBook.id, word.word);
    
    _moveToNextWord();
  }

  void _onForgotten() async {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    // 重置重复次数
    await WordBookService.updateWordRepeatCount(widget.wordBook.id, word.word, 0);
    
    _moveToNextWord();
  }

  void _moveToNextWord() {
    setState(() {
      _currentIndex++;
      _showDetails = false;
    });
    
    if (_currentIndex < widget.words.length) {
      _checkIfLastRepetition();
      _playWhatsThis();
    } else {
      // 所有单词都已学习完毕
      _showCompletionDialog();
    }
  }

  void _showCompletionDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('恭喜！'),
        content: Text('您已完成本轮跟读学习。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              Navigator.of(context).pop(); // 返回上一页
            },
            child: Text('返回'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (widget.words.isEmpty || _currentIndex >= widget.words.length) {
      return Scaffold(
        appBar: AppBar(
          title: Text('跟读模式'),
        ),
        body: Center(
          child: Text('没有更多单词了'),
        ),
      );
    }

    final WordCard currentWord = widget.words[_currentIndex];

    // 底部操作按钮 - 仅在最后一次重复时显示
    Widget? bottomActions;
    if (_isLastRepetition && _showDetails) {
      bottomActions = Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 记住按钮（红心）
          ElevatedButton(
            onPressed: _onRemembered,
            style: ElevatedButton.styleFrom(
              shape: CircleBorder(),
              padding: EdgeInsets.all(20),
              backgroundColor: Colors.red,
            ),
            child: Icon(Icons.favorite, color: Colors.white),
          ),
          
          // 遗忘按钮（黑叉）
          ElevatedButton(
            onPressed: _onForgotten,
            style: ElevatedButton.styleFrom(
              shape: CircleBorder(),
              padding: EdgeInsets.all(20),
              backgroundColor: Colors.black,
            ),
            child: Icon(Icons.close, color: Colors.white),
          ),
        ],
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('跟读模式'),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.blue.withOpacity(0.3),
              Colors.purple.withOpacity(0.3),
            ],
          ),
        ),
        child: Column(
          children: [
            // 进度指示器
            Padding(
              padding: EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '重复次数: ${currentWord.repeatCount + 1}/5',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            
            // 单词卡片
            Expanded(
              child: GestureDetector(
                onTap: _onCardTap,
                child: Container(
                  margin: EdgeInsets.all(16),
                  child: WordCardWidget(
                    wordCard: currentWord,
                    showDetails: _showDetails,
                    onTap: _onCardTap,
                    bottomActions: bottomActions,
                  ),
                ),
              ),
            ),
            
            // 导航按钮
            if (!_isLastRepetition || (_isLastRepetition && !_showDetails))
              Padding(
                padding: EdgeInsets.all(16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 上一个按钮
                    IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: _currentIndex > 0
                          ? () {
                              setState(() {
                                _currentIndex--;
                                _showDetails = false;
                              });
                              _checkIfLastRepetition();
                              _playWhatsThis();
                            }
                          : null,
                    ),
                    
                    // 下一个按钮
                    IconButton(
                      icon: Icon(Icons.arrow_forward),
                      onPressed: () {
                        _moveToNextWord();
                      },
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }
} 